package com.football;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import data.FootBallMemberConstants;
import model.FootBallMember;

public class DeletePlayerDialog extends JDialog{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	public DeletePlayerDialog(){
		Point p1 = new Point(200,200);
		this.setLocation(p1);
		
		Dimension d1 = new Dimension();
		d1.setSize(300, 300);
		this.setSize(d1);
		
		this.setLayout(null);
		
		JLabel label1 = new JLabel("Player Name");
		Point p2 = new Point(50,50);
		label1.setLocation(p2);
		Dimension d2 = new Dimension();
		d2.setSize(100, 30);
		label1.setSize(d2);
		this.add(label1);
		
		final JTextField name = new JTextField();
		Point p3 = new Point(150,50);
		name.setLocation(p3);
		Dimension d3 = new Dimension();
		d3.setSize(100, 25);
		name.setSize(d3);
		this.add(name);
		
		JButton but1 = new JButton("Delete");
		Point p4 = new Point(100,100);
		but1.setLocation(p4);
		Dimension d4 = new Dimension();
		d4.setSize(100, 25);
		but1.setSize(d4);
		this.add(but1);
		
		but1.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {

				String playerName = name.getText();
				String msg = "Player name can not be empty!";
				if(playerName==null){
					JOptionPane.showMessageDialog(null, msg);
					return;
				}
				
				if(playerName.equals("")){
					JOptionPane.showMessageDialog(null, msg);
					return;
				}
				
				List<FootBallMember> list =  FootBallMemberConstants.footBallMembers;
				
				if(list == null){
					String msg1 = "Error happens1";
					JOptionPane.showMessageDialog(null, msg1);
					return;
				}
				
				if(list.isEmpty()){
					String msg2 = "There is no Football Member!";
					JOptionPane.showMessageDialog(null, msg2);
					return;
				}
				
				//find the player and delete
				List<Integer> tobedelete = new ArrayList<Integer>();
				int i=0;
				for(FootBallMember member : list){
					String name = member.getName();
					if(playerName.equals(name)){
						tobedelete.add(i);
					}
					i++;
				}
				
				if(tobedelete.size()>0){
					for(int j=tobedelete.size()-1;j>=0;j--){
						int t = tobedelete.get(j);
						list.remove(t);
					}
					String msg3 = "Delete Successfully!";
					JOptionPane.showMessageDialog(null, msg3);
					
				}else{
					String msg4 = "Can not find this player!";
					JOptionPane.showMessageDialog(null, msg4);
				}
				
			}
		});
		
		this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		this.setVisible(true);
	}
}
